package org.edu.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.edu.bean.Pass;
import org.edu.bean.User;
import org.edu.bean.UserInfo;
import org.edu.service.UserService;
import org.edu.utils.StringDealUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserInfoController extends ActionSupport{
	
	@Resource
	UserService userService ;
	
	private Pass pass ;
	private User user ;
	private UserInfo usinfo;
	private Integer id;
	public String rightTop(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession() ;
		user = (User)session.getAttribute("user");
		return SUCCESS;
	}
	public String changePass(){
		if(pass == null){
			return "page";
		}else{
			if(!pass.getNew1().equals(pass.getNew2())){
				return "false";
			}else{
				HttpServletRequest request = ServletActionContext.getRequest();
				HttpSession session = request.getSession() ;
				user = (User)session.getAttribute("user");
				if(user.getPassword().equals(StringDealUtil.getMD5Str(pass.getOld()))){
					user.setPassword(StringDealUtil.getMD5Str(pass.getNew1()));
					userService.updateUser(user);
					return SUCCESS;
				}else{
					return "false";
				}
				
			}
			
		}
	}
	
	public String editUserInfo(){
		if (null!=usinfo){
			try {
				userService.saveOrUpdate(usinfo);
				id=usinfo.getUserId();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println(id);
		if (null!= id){
			
			UserInfo usinfo=null;
			try {
				usinfo = (UserInfo) userService.findUsInfoByUserId(id);
				User u=(User)userService.findById(User.class,id);
				ActionContext.getContext().put("u", u);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null==usinfo)
			{
			usinfo=new UserInfo();
			usinfo.setUserId(id);
			}
			ActionContext.getContext().put("usinfo", usinfo);
			
		}
		return SUCCESS;
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public Pass getPass() {
		return pass;
	}
	public void setPass(Pass pass) {
		this.pass = pass;
	}
	public UserInfo getUsinfo() {
		return usinfo;
	}
	public void setUsinfo(UserInfo usinfo) {
		this.usinfo = usinfo;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	
}
